package org.helgoboss.document_database_orient_impl

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx
import org.helgoboss.document_database._

class OrientDatabase(private[document_database_orient_impl] val delegate: ODatabaseDocumentTx) extends Database {
    def buckets = {
        import scala.collection.JavaConversions._
        delegate.getMetadata.getSchema.getClasses.filter { oClass =>
            oClass.getName != "ORole" && oClass.getName != "OUser"
        }.map { oClass =>
            new OrientBucket(database = this, delegate = oClass).asInstanceOf[Bucket]
        }
    }
    
    def findBucket(id: String) = {
        val oClass = delegate.getMetadata.getSchema.getClass(id)
        if(oClass == null) {
            None
        } else {
            Some(
                new OrientBucket(database = this, delegate = oClass)
            )
        }
    }
    
    def addBucket(id: String) = {
        require(!bucketExists(id), "Bucket [" + id + "] already exists")
        val schema = delegate.getMetadata.getSchema
        val oClass = schema.createClass(id)
        schema.save
        new OrientBucket(database = this, delegate = oClass)
    }
    
    def bucketExists(id: String) = findBucket(id).isDefined
    
    def removeBucket(bucket: Bucket) {
        bucket.clear
        val schema = delegate.getMetadata.getSchema
        schema.dropClass(bucket.asInstanceOf[OrientBucket].delegate.getName)
        schema.save()
    }
}